Finessing the sort keys
Now, we want to apply the same kind of sorting behavior to the Author(s) column of our table. By adding the sort-alpha class to its table header cell, the Author(s)
column can be sorted with our existing code. Ideally authors should be
sorted by last name, not first. Since some books have multiple authors,
and some authors have middle names or initials listed, we need outside
guidance to determine what part of the text to use as our sort key. We
can supply this guidance by wrapping the relevant part of the cell in a
tag:
<tr>
<td><img src="../images/covers/small/1847192386.png"
width="49" height="61" alt="Building Websites with
Joomla! 1.5 Beta 1" />
</td>
<td>Building Websites with Joomla! 1.5 Beta 1</td>
<td>Hagen <span class="sort-key">Graf</span></td>
<td>Feb 2007</td>
<td>$40.49</td>
</tr>
<tr>
<td><img src="../images/covers/small/1904811620.png"
width="49" height="61" alt="Learning Mambo: A
Step-by-Step Tutorial to Building Your Website" />
</td>
<td>Learning Mambo: A Step-by-Step Tutorial to Building
Your Website
</td>
<td>Douglas <span class="sort-key">Paterson</span></td>
<td>Dec 2006</td>
<td>$40.49</td>
</tr>
Now, we have to modify our sorting code to take this tag into account without disturbing the existing behavior for the Title
column, which is already working well. By prepending the marked sort
key to the key we have previously calculated, we can sort first on the
last name if it is called out, but on the whole string as a fallback:
$.each(rows, function(index, row) {
var $cell = $(row).children('td').eq(column);
row.sortKey = $cell.find('.sort-key').text().toUpperCase()
+ ' ' + $cell.text().toUpperCase();
});
Sorting by the Author(s) column now uses the provided key, thereby sorting by last name:
If two last names are identical, the sort uses the entire string as a tiebreaker for positioning.